﻿
using MiscUtil.IO;
using Net.http;
using PacketDotNet;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;

namespace HBase {
    public class TCPFactray<T> where T: MyTcpClient ,new() {
        private static Socket ServerTcp;

        static List<T> myTcpClientList=new List<T>();

        public static void  init() {

             ServerTcp = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //绑定IP和端口
            String[] addr = BaseConfig.tcpPort.Split(':');
            IPAddress iPAddress = IPAddress.Parse(addr[0]);
            EndPoint endPoint = new IPEndPoint(iPAddress, int.Parse(addr[1]));
            ServerTcp.Bind(endPoint);
            //监听，等待客户端进行链接
            Console.WriteLine("开始监听");
            ServerTcp.Listen(10000);//开始监听，100为最大连接数
            Console.WriteLine("等待客户端链接");

            System.Threading.Tasks.Task.Factory.StartNew(() => {
                CreateNew();
            });
          
        }

      

       static void CreateNew() {
            while (true) {
              
                Socket client = ServerTcp.Accept();//接收客户端；实际上是暂停当前线程
                for (int i = 0; i < myTcpClientList.Count; i++) {
                    T t = myTcpClientList[i];
                    if (t.isCloss) {
                        myTcpClientList.RemoveAt(i);
                        i--;
                    }
                    if (DateTime.Now.Ticks - t.lastUse.Ticks > 3600L * HUtil.ticksSecRate * 4) {
                        t.close();
                    }

                }
                T c=new T();
                c.fill(client);
                myTcpClientList.Add(c);
               
            }

        }
 
       
    }

}